package com.lxq.web.servlet.mng;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.lxq.common.DaoFactory;
import com.lxq.dao.CardDao;
import com.lxq.dao.OrderRechargeDao;
import com.lxq.dao.UserCardDao;
import com.lxq.entity.OrderRecharge;
import com.lxq.web.servlet.common.BaseServlet;

@WebServlet("/app/mng/order")
public class OrderRechargeServlet extends BaseServlet {
	private static final long serialVersionUID = -5141536770286197321L;
	private OrderRechargeDao orderRechargeDao = DaoFactory.getInstance("orderRechargeDao", OrderRechargeDao.class);
	private CardDao cardDao = DaoFactory.getInstance("cardDao", CardDao.class);
	private UserCardDao userCardDao = DaoFactory.getInstance("userCardDao", UserCardDao.class);

	@Override
	public void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phoneNumber = request.getParameter("phone");
		String cardNumber = request.getParameter("cardnumber");
		String orderAmount = request.getParameter("orderamount");

		JSONObject json = new JSONObject();
		Calendar cale = Calendar.getInstance();

		try {
			if (phoneNumber != null && cardNumber != null && orderAmount != null) {

				if (userCardDao.findByCardNumberPhone(phoneNumber, cardNumber) != null) {

					if (cardDao.findByCardNumber(cardNumber) != null) {

						switch (cardDao.findByCardNumber(cardNumber).getCardState()) {
						case 0:
							json.put("success", false);
							json.put("reason", "卡已挂失，不能充值！");
							break;

						case 1:
							json.put("success", false);
							json.put("reason", "卡未绑定，不能充值！");
							break;

						default: {

							Date orderTime = new Date(cale.getTimeInMillis());
							String orderId = UUID.randomUUID().toString();
							int orderState = 0; // 默认创建时是下单成功状态，即未支付

							OrderRecharge order = new OrderRecharge();
							order.setOrderId(orderId);
							order.setPhoneNumber(phoneNumber);
							order.setCardNumber(cardNumber);
							order.setOrderAmount(orderAmount);
							order.setOrderTime(orderTime);
							order.setOrderState(orderState);

							orderRechargeDao.save(order);
							json.put("success", true);
							json.put("order", new JSONObject(order));
							break;
						}

						}

					} else {
						json.put("success", false);
						json.put("reason", "所要充值的卡不存在！");
					}
				} else {
					json.put("success", false);
					json.put("reason", "该卡未绑定到该用户！");
				}
			} else {
				json.put("success", false);
				json.put("reason", "缺少必要参数！");
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}

	@Override
	public void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String phoneNumber = request.getParameter("phone");
		String cardNumber = request.getParameter("cardnumber");
		JSONObject json = new JSONObject();

		try {
			if (phoneNumber != null && cardNumber != null) {

				List<OrderRecharge> orders = null;

				orders = orderRechargeDao.findOrder(phoneNumber, cardNumber);

				if (orders.size() <= 0) {
					json.put("success", false);
					json.put("reason", "无订单记录！");
				} else {
					json.put("success", true);
					json.put("orders", new JSONArray(orders));
				}

			} else {
				json.put("success", false);
				json.put("reason", "缺少必要参数！");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}

	@Override
	public void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String orderId = request.getParameter("orderid");

		JSONObject json = new JSONObject();
		OrderRecharge order = orderRechargeDao.findById(orderId);

		try {
			if (orderId != null) {

				if (order != null) {
					List<Object> list = new ArrayList<Object>();
					// 对订单的状态进行更新，更新为已支付订单
					orderRechargeDao.updateOrderState(orderId, 1);
					// 对卡表的卡余额进行更新
					String balance = cardDao.findByCardNumber(order.getCardNumber()).getCurrentBalance();
					Integer newBalance = Integer.valueOf(balance) + Integer.valueOf(order.getOrderAmount());
					cardDao.updateCurrentBalance(order.getCardNumber(), newBalance.toString());

					list.add(orderRechargeDao.findById(orderId));
					list.add(cardDao.findByCardNumber(order.getCardNumber()));

					json.put("success", true);
					json.put("message", new JSONArray(list));

				} else {
					json.put("success", false);
					json.put("reason", "订单id出错,未找到该订单！");
				}

			} else {
				json.put("success", false);
				json.put("reason", "支付失败,缺少订单id！");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json.toString());
		response.getWriter().flush();
	}
}
